# -*- coding: utf-8 -*-

import os
import sys
import logging
from logging import handlers

import config
from util import create_folder

logger = logging.getLogger(config.flask_app_log)


def init_logger(logger):
    """初始化日志配置"""
    # 控制台输出日志
    console_handler = logging.StreamHandler(stream=sys.stdout)

    # 创建日志目录
    create_folder(config.log_file_name)

    # 按大小分割日志文件
    file_handler = handlers.RotatingFileHandler(filename=config.log_file_name,
                                                maxBytes=config.log_file_max_bytes,
                                                backupCount=config.log_file_backup_count)

    # 按时间分割日志文件
    # file_handler = handlers.TimedRotatingFileHandler(filename=config.log_file_name,
    #                                                  when='D', interval=10,
    #                                                  backupCount=config.log_file_backup_count)
    """
    when=''
    S
    M
    H
    D
    W
    midnight
    """
    # 日志格式
    console_handler.setFormatter(fmt=logging.Formatter(config.log_console_format))
    file_handler.setFormatter(fmt=logging.Formatter(config.log_file_format))

    # 日志级别
    console_handler.setLevel(logging.DEBUG)
    file_handler.setLevel(logging.DEBUG)
    logger.setLevel(logging.DEBUG)

    # 日志对象添加处理器
    logger.addHandler(console_handler)
    logger.addHandler(file_handler)

    logger.debug('init logger')
    pass


if __name__ == '__main__':
    logger = logging.getLogger(config.flask_app_log)
    init_logger(logger)
    pass
